package code;

import java.io.File;

import javafx.event.EventHandler;
import javafx.scene.control.TreeItem;

public class FolderTreeItem extends TreeItem<File> {
	private boolean notChildrenLoaded = true;
	private boolean isRoot;

	public FolderTreeItem(File file, boolean isRoot) {
		super(file);
		this.isRoot = isRoot;
	}

	public void loadChildren() {
		if (notChildrenLoaded) {
			notChildrenLoaded = false;

			File[] children = null;

			if (!isRoot) {
				File dir = this.getValue();
				children = dir.listFiles();
			} else {
				children = File.listRoots();
			}
			if (children == null) {
				return;
			}
			for (File child : children) {
				if (child.isDirectory() && (isRoot || !child.isHidden())) {
					FolderTreeItem item = new FolderTreeItem(child, false);

					item.addEventHandler(FolderTreeItem.branchExpandedEvent(),
							new EventHandler<TreeItem.TreeModificationEvent<File>>() {

								@Override
								public void handle(TreeModificationEvent<File> event) {
									for (TreeItem<File> child : event.getSource().getChildren()) {
										((FolderTreeItem) child).loadChildren();
									}
								}

							});

					this.getChildren().add(item);
				}
			}
		}
	}
}
